var mongoose = require('mongoose');
const Cate = require('../models/cate.model');
exports.create = function(req, res, next) {
  const cate = new Cate(req.body);
  cate.save().then(data => {
    res.json(data);
  });
};

exports.update = function(req, res, next) {
  // 找到那个对象以后再修改
  const id = req.params.id;
  Cate.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    res.json(data); // 但是请注意，这里的data是没有修改之前的数据
  });
};

exports.getData = function(req, res, next) {
  const id = req.params.id;

  Cate.findById(id, (err, data) => {
    res.json(data);
  });
};

exports.remove = function(req, res, next) {};

function reverseTree(data, pid) {
  var result = [],
    temp;

  var data = JSON.parse(JSON.stringify(data)); // 原先这个data是数据模型中的data，原来数据模型中是没有children这个字段的，将数据模型对象转成字符串，再转成对象，现在的对象就从数据模型对象转成了javascript的object

  for (var i in data) {
    if (data[i].parentId === pid) {
      result.push(data[i]);

      temp = reverseTree(data, data[i]._id);

      if (temp.length > 0) {
        data[i].children = temp;
      }
    }
  }

  return result;
}

exports.list = function(req, res, next) {
  var type = req.params.type || 1;
  Cate.find({ type: type }, (err, data) => {
    var rpTree = reverseTree(data, null);
    res.json(rpTree);
  });
};
